package pers.archives.loginToken.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.builders.InMemoryClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import pers.archives.loginToken.properties.OAuth2ClientProperties;
import pers.archives.loginToken.properties.OAuth2Properties;

/* 认证服务器
 *@program:archives-parent
 *@author: 赵浩浩
 *@Time: 2020/9/12  13:18
 */
@Configuration
@EnableAuthorizationServer
public class ArchivesAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired(required = false)
    private AuthenticationManager authenticationManager;
    @Autowired(required = false)
    private UserDetailsService userDetailsService;
    @Autowired(required = false)
    private OAuth2Properties oAuth2Properties;

    @Autowired
    private TokenStore tokenStore;



    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore) //设置token存放位置 redis
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService);
    }

    /**
     * 指定应用的clientId
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        InMemoryClientDetailsServiceBuilder inMemoryClientDetailsServiceBuilder = clients.inMemory();//存放与内存
        for (OAuth2ClientProperties client : oAuth2Properties.getClients()) {
            inMemoryClientDetailsServiceBuilder
                    .withClient(client.getClientId()) //指定client-id
                    .secret(client.getClientSecret()) //
                    .accessTokenValiditySeconds(client.getAccessTokenValiditySeconds()) //token存在的时间
                    .authorizedGrantTypes("password", "refresh_token") //授权模式
                    .scopes("all");
        }


    }
}
